
import {
    ATTR,
    TEXT,
    REMOVE,
    REPLACE
} from './patchType';

import {
    setAttrs, render
} from './virtualDom'

import Element from './Element'


let finalPatches = {};
let rnIndex = 0;



function doPatch(rDom,patches) {
    finalPatches = patches;
    rNodeWalk(rDom);
}

function rNodeWalk(rNode) {
    // rnPatch = [{
    //  0: { type: 'ATTR'
    //       attrs: { class: 'list-wrap'}
    //     }
    // }]
    const rnPatch = finalPatches[rnIndex ++];
    const childNodes = rNode.childNodes;
    // rNode = <ul>
    // childNodes = 各种<li>

    [...childNodes].map((child) => {
        // 递归
        rNodeWalk(child);
    })

    if(rnPatch){
        patchAction(rNode, rnPatch);
    }

}

function patchAction(RealNode, RealNodePatch) {
    RealNodePatch.map(patch => {
        switch (patch.type) {
            case ATTR:
                Object.keys(patch.attrs).forEach(key => {
                    let value = patch.attrs[key];
                    if(value) {
                        // 直接改className
                        RealNode.className = value;
                        setAttrs(RealNode, key, value);
                    } else {
                        console.log('----', RealNode);
                        RealNode.removeAttribute(key);
                    }
                })
                break;
            case TEXT:
                // 直接替换
                RealNode.textContent = patch.text;
                break;
            case REMOVE:
                // 父节点删除子节点
                RealNode.parentNode.removeChild(RealNode);
                break;
            case REPLACE:
                const newNode = (patch.newNode instanceof Element)
                        ? render(patch.newNode)
                        : document.createTextNode(patch.newNode);
                // 父节点替换子节点
                RealNode.parentNode.replaceChild(newNode, RealNode);
                break;
            default:
                break;
        }
    })
}


export default doPatch;
